package com.ruoyi.operation.cmdb;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import sun.net.www.http.HttpClient;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;
/**
 * @Author Zzneko
 * @Date 2025/6/16 13:45
 * @Descprition
 **/
public class CmdbUtils {
    private static final String URL = "https://cmdb.veops.cn/api/v0.1/ci/s";
    private static final String KEY = "2d029fc1df6f405abbf64ac0a82de3d7";
    private static final String SECRET = "L*EP2mW!5q1aw~s^zVKMupv9XQ$tHhJT";

    public static Map<String, Object> buildApiKey(String path, Map<String, Object> params,String key,String secret) {
        if (params == null) {
            params = new HashMap<>();
        }

        // Filter and sort parameters
        String values = params.entrySet().stream()
            .filter(entry -> !"_key".equals(entry.getKey()))
            .filter(entry -> !"_secret".equals(entry.getKey()))
            .filter(entry -> !(entry.getValue() instanceof Map))
            .filter(entry -> !(entry.getValue() instanceof List))
            .sorted(Map.Entry.comparingByKey())
            .map(entry -> entry.getValue().toString())
            .collect(Collectors.joining());

        try {
            // Create SHA-1 hash
            String secretInput = path + secret + values;
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            byte[] hashBytes = digest.digest(secretInput.getBytes(StandardCharsets.UTF_8));
            String secretHash = bytesToHex(hashBytes);

            // Add authentication parameters
            params.put("_secret", secretHash);
            params.put("_key", key);

        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-1 algorithm not available", e);
        }

        return params;
    }

    public static String buildQueryStr(Map<String, Object> signedParams) {
        return signedParams.entrySet().stream()
            .map(entry -> {
                try {
                    return entry.getKey() + "=" + URLEncoder.encode(entry.getValue().toString(), String.valueOf(StandardCharsets.UTF_8));
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
            })
            .collect(Collectors.joining("&"));
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    public static String getCi(Map<String, Object> payload){
        // Parse URL path
        URI uri = URI.create(URL);
        String path = uri.getPath();
        // Build authenticated parameters
        Map<String, Object> signedParams = buildApiKey(path, payload,KEY,SECRET);

        // Build query string
//        String queryString = signedParams.entrySet().stream()
//            .map(entry -> {
//                try {
//                    return entry.getKey() + "=" + URLEncoder.encode(entry.getValue().toString(), String.valueOf(StandardCharsets.UTF_8));
//                } catch (UnsupportedEncodingException e) {
//                    throw new RuntimeException(e);
//                }
//            })
//            .collect(Collectors.joining("&"));
        String queryString = buildQueryStr(signedParams);
//
        // Create and send HTTP request
//        HttpClient client = HttpClient.newBuilder().build().newHttpClient();
//        HttpRequest request = HttpRequest.newBuilder()
//                .uri(URI.create(URL + "?" + queryString))
//                .GET()
//                .build();
//        HttpResponse response = HttpRequest.of(String.valueOf(URI.create(URL + "?" + queryString))).execute();
        String string = HttpUtil.get(URL + "?" + queryString);
        JSONObject object = JSON.parseObject(string);
        List<Map<String,String>> o = ((List<Map<String,String>>) object.get("result"));
        Map<String, String> map = o.get(0);
        System.out.println(map);
//        return response.body();
        return string;
    }

    public static void main(String[] args) throws Exception {
        // Example usage
        Map<String, Object> payload = new HashMap<>();
        payload.put("q", "_type:32");
//        payload.put("param2", 123);

        String response = getCi(payload);
//        System.out.println(response);
    }
}

